<template>
  <view class="c-pd">
    <view v-if="state.historyReportList.length > 0">
      <van-cell-group inset title="历史上报">
        <van-cell :title="'地址：' + item.site" :value="item.createDate" v-for="(item, index) in state.historyReportList" :key="index" />
      </van-cell-group>
    </view>
    <view v-if="state.alarmId">
      <van-cell-group inset title="火灾信息">
        <van-cell :title="state.alarmAddress" :value="state.alarmDate" />
      </van-cell-group>
    </view>
    <view>
      <van-cell-group inset title="受困上报">
        <van-cell center title="受困人数" use-label-slot>
          <view slot="right-icon">
            <van-stepper
              :value="state.trapNum"
              @change="
                (e: any) => {
                  state.trapNum = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <SelectLocation ref="childComp" :isGetUserAddress="false" @returnData="setLocation" @clearData="clearLocation" />
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="详细位置" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="state.site"
              type="textarea"
              placeholder="请输入详细位置"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  state.site = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
      <view class="mt-3">
        <van-button type="primary" block @click="handleSelectAddress">获取位置</van-button>
      </view>
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="受困描述" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="state.trapDesc"
              type="textarea"
              placeholder="请输入受困描述"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  state.trapDesc = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <UploadFile @clearUrl="clearUrl" @returnUrl="setVideoUrl" title="上传视频"></UploadFile>
    </view>
    <view class="mt-3" :style="{ marginBottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="handleSendReport">上报</van-button>
    </view>
    <van-dialog use-slot title="请选择一项报警" confirm-button-text="确认" confirm-button-color="#ffc330" :show="state.popupShow" :before-close="onBeforeClose">
      <view class="dialog_box">
        <view
          v-for="(item, index) in state.fireInformationInfoList.alarmList"
          :key="index"
          :class="{
            'cell_box_select mb-3': item.alarmId === state.alarmId,
            'mb-3': true,
          }"
          @click="
            state.alarmId = item.alarmId;
            state.alarmDate = item.createDate;
            state.alarmAddress = item.address;
          "
        >
          <van-cell-group :key="index" inset>
            <van-cell title="火灾地址" :label="item.address" />
            <van-cell title="火灾时间" :label="item.createDate" />
          </van-cell-group>
        </view>
      </view>
    </van-dialog>
  </view>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store';
import UploadFile from '../component/UploadFile.vue';
import SelectLocation from '../component/SelectLocation.vue';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';
import Location from '@/utils/location';
import HomeRequest from '@/request/homeRequest';
import { navigate } from '@/utils/navigate';

interface IState {
  alarmId: number;
  alarmAddress: string;
  alarmDate: string;
  buildId: number;
  buildName: string;
  floorId: number;
  floorName: string;
  houseNumber: string;
  houseNumberId: number;
  site: string;
  trapDesc: string;
  trapNum: number;
  trapVideos: string;
  unitId: number;
  unitName: string;
  latitude: string;
  longitude: string;
  beeperId: number;
  fireInformationInfoList: IFireInformation;
  historyReportList: IHistoryReport[];
  popupShow: boolean;
}

const store = useAppStore();

const state = reactive<IState>({
  beeperId: store.$state.beeperId,
  alarmId: 0,
  alarmAddress: '',
  alarmDate: '',
  buildId: 0,
  buildName: '',
  floorId: 0,
  floorName: '',
  houseNumber: '',
  houseNumberId: 0,
  site: '',
  trapDesc: '',
  trapNum: 1,
  trapVideos: '',
  unitId: 0,
  unitName: '',
  latitude: '',
  longitude: '',
  fireInformationInfoList: {
    alarmList: [],
    buildId: 0,
    buildName: '',
    floorId: 0,
    floorName: '',
    houseNumber: '',
    houseNumberId: 0,
    type: 0,
    unitId: 0,
    unitName: '',
  },
  historyReportList: [],
  popupShow: false,
});

const { showModal } = useModal();

const { showToast } = useToast();

const childComp = ref();

onLoad(() => {
  getFireInformation();
});

//清空楼栋层
const clearLocation = () => {
  Object.assign(state, {
    buildId: 0,
    buildName: '',
    unitId: 0,
    unitName: '',
    floorId: 0,
    floorName: '',
    houseNumberId: '',
    houseNumber: '',
  });
};

//设置楼栋层
const setLocation = (payload: { item: IBuildingTreeRes[]; isUpload: boolean }) => {
  if (payload.item.length >= 1 && payload.item[0].id) {
    state.buildId = Number(payload.item[0].id);
    state.buildName = payload.item[0].name;
  }
  if (payload.item.length >= 2 && payload.item[1].id) {
    state.unitId = Number(payload.item[1].id);
    state.unitName = payload.item[1].name;
  }
  if (payload.item.length >= 3 && payload.item[2].id) {
    state.floorId = Number(payload.item[2].id);
    state.floorName = payload.item[2].name;
  }
  if (payload.item.length >= 4 && payload.item[3].id) {
    state.houseNumberId = Number(payload.item[3].id);
    state.houseNumber = payload.item[3].name;
  }
};

//清空视频
const clearUrl = () => {
  state.trapVideos = '';
};

//获取视频地址
const setVideoUrl = ({ url }: { url: string }) => {
  state.trapVideos = url;
};

const handleSendReport = () => {
  const { beeperId, alarmId, buildId, buildName, floorId, floorName, houseNumber, houseNumberId, site, trapDesc, trapNum, trapVideos, unitId, unitName, latitude, longitude } = state;
  let params: any = { beeperId, alarmId, buildId, buildName, floorId, floorName, houseNumber, houseNumberId, site, trapDesc, trapNum, trapVideos, unitId, unitName, hasLoading: true };
  if (!buildName && !site) {
    showModal('所在楼层或详细位置必须填写一个');
    return false;
  }
  if (latitude && longitude) {
    params.latitude = latitude.toString();
    params.longitude = longitude.toString();
  }
  HomeRequest.SendReportAlarmTrap(params).then((res) => {
    if (res.status === 0) {
      showToast('上报成功', 'success');
      setTimeout(() => {
        navigate({ url: '', type: 'navigateBack' });
      }, 1000);
    }
  });
};

/**
 * 选择位置
 */
const handleSelectAddress = async () => {
  const address = await Location.positioningLatitudeLongitude();
  if (address?.latitude && address.longitude) {
    showModal('选择地址需要清除已选择的楼栋层吗？', {
      showCancel: true,
      cancelText: '不清除',
      confirmText: '清除',
      success: async () => {
        state.site = '';
        childComp.value.clearAddress();
        const chooseRes = await uni.chooseLocation({
          latitude: address?.latitude,
          longitude: address?.longitude,
        });
        state.site = chooseRes.address;
        state.latitude = String(chooseRes.latitude);
        state.longitude = String(chooseRes.longitude);
      },
      fail: async () => {
        const chooseRes = await uni.chooseLocation({
          latitude: address?.latitude,
          longitude: address?.longitude,
        });
        state.site = chooseRes.address;
        state.latitude = String(chooseRes.latitude);
        state.longitude = String(chooseRes.longitude);
      },
    });
  }
};

const getFireInformation = () => {
  HomeRequest.GetFireInformation({
    hasLoading: true,
    beeperId: state.beeperId,
  }).then((res) => {
    if (res.status === 0) {
      state.fireInformationInfoList = res.data;
      if (state.fireInformationInfoList.alarmList.length >= 1) {
        state.popupShow = true;
      } else {
        showModal('24小时内无火灾报警，无需上报', {
          confirmText: '新增报警',
          cancelText: '取消上报',
          showCancel: true,
          success: () => {
            navigate({ url: '/subcontract/home/fireDetection/index?btnId=0', type: 'redirectTo' });
          },
          fail: () => {
            navigate({ url: '', type: 'navigateBack' });
          },
        });
      }
    }
  });
};

const getHistoryReport = () => {
  HomeRequest.GetTrapHistoryReport({
    hasLoading: true,
    alarmId: state.alarmId,
  }).then((res) => {
    if (res.data.length > 0) {
      state.historyReportList = res.data.map((item) => {
        return {
          ...item,
          site: item.buildName + item.unitName + item.floorName + item.houseNumber + item.site,
        };
      });
    }
  });
};

const onBeforeClose = (action: string) => {
  if (action === 'confirm') {
    if (!state.alarmId) {
      showModal('请选择一项火灾信息');
      return false;
    } else {
      getHistoryReport();
      state.popupShow = false;
      return true;
    }
  } else {
    return true;
  }
};
</script>

<style scoped lang="scss">
:deep(.van-panel) {
  border-radius: 16rpx !important;
}

:deep(.van-cell-group__title) {
  padding-left: 0;
}

:deep(.van-dialog__header) {
  padding-top: 24rpx;
  padding-bottom: 24rpx;
}

.dialog_box {
  overflow: auto;
  padding: 24rpx 24rpx 0;
  max-height: 800rpx;
  background: #f3f3f3;
}

.cell_box_select {
  border: 1px solid #ffc330;
  border-radius: 16rpx !important;
}
</style>
